package com.cnvp.paladin.utils.beetl.fn;

import org.apache.commons.lang3.StringEscapeUtils;
import org.beetl.core.Format;
import org.owasp.validator.html.*;

import com.jfinal.kit.PathKit;

public class XSSDefenseFormat implements Format {
 
 
    @Override
    public Object format(Object data, String pattern) {
        if (null == data) {
            return null;
        } else {
 
            try {
                Policy policy = Policy.getInstance(PathKit.getRootClassPath()+"/antisamy.xml");  //antisamy.xml采用官方给出的ｅｂａｙ的模板
                AntiSamy as = new AntiSamy(policy);
 
                String content = (String) data;
                if ("escape".equals(pattern)) {
                    content = StringEscapeUtils.escapeHtml3(content);
                }
 
                // clean content
                CleanResults cr = as.scan(content);
                content = cr.getCleanHTML();
 
                return content;
 
            } catch (ScanException e) {
            	System.out.println("ScanException");
                return "系统错误";
            } catch (PolicyException e) {
            	System.out.println("PolicyException");
                return "系统错误";
            }
 
        }
    }
}

